package com.oliet.common.vo.permission;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.oliet.entity.Permissions;
import lombok.Data;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jiaZhenpeng
 * @Title: PermissionTreeVO
 * @Package com.oliet.common.vo.permission
 * @Description: 权限树节点
 * @date 2023-12-06 17:15
 */
@Data
public class PermissionTreeNodeVO {

    /**
     * 权限ID
     */
    private Long id;

    /**
     * 权限编码
     */
    private String code;

    /**
     * 权限名称
     */
    private String permissionName;

    /**
     * 权限类型
     */
    private String permissionType;

    /**
     * 描述
     */
    private String description;

    /**
     * 父权限ID
     */
    private Long parentId;

    /**
     * 菜单地址
     */
    private String resourceAddress;

    /**
     * 权限层级
     */
    private Integer level;

    /**
     * 显示位置
     */
    private String displayPosition;

    /**
     * 子节点
     */
    private List<PermissionTreeNodeVO> children;


    public static List<PermissionTreeNodeVO> buildTree(List<Permissions> poList) {
        List<PermissionTreeNodeVO> result = Lists.newArrayList();
        if (CollectionUtil.isEmpty(poList)){
            return result;
        }
        //找到父权限数据
        List<Permissions> rootList = poList.stream().filter(it -> it.getParentId() == 0L).collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(rootList)){
            rootList.forEach(it -> {
                PermissionTreeNodeVO vo = new PermissionTreeNodeVO();
                BeanUtil.copyProperties(it, vo);
                List<PermissionTreeNodeVO> childNodes = setChildNodes(it, poList);
                vo.setChildren(childNodes);
                result.add(vo);
            });
        }
        return result;
    }

    public static List<PermissionTreeNodeVO> setChildNodes(Permissions po, List<Permissions> poList) {
        List<PermissionTreeNodeVO> result = Lists.newArrayList();
        if (CollectionUtil.isEmpty(poList) || po == null){
            return result;
        }
        poList.stream().filter(it -> it.getParentId().equals(po.getId())).forEach(it -> {
            PermissionTreeNodeVO vo = new PermissionTreeNodeVO();
            BeanUtil.copyProperties(it, vo);
            List<PermissionTreeNodeVO> childNodes = setChildNodes(it, poList);
            vo.setChildren(childNodes);
            result.add(vo);
        });
        return result;
    }

}
